/*
 * Copyright 2020-2030 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.gitee.minimalismstyle.fresh.common.web.resolver

import com.gitee.minimalismstyle.fresh.common.core.domain.QueryParams
import com.gitee.minimalismstyle.fresh.common.core.domain.Simple
import org.springframework.context.annotation.Configuration
import org.springframework.core.MethodParameter
import org.springframework.web.bind.support.WebDataBinderFactory
import org.springframework.web.context.request.NativeWebRequest
import org.springframework.web.method.support.HandlerMethodArgumentResolver
import org.springframework.web.method.support.ModelAndViewContainer


/**
 *  通用查询参数解析器
 * @author maoxiaodong
 */
@Configuration
class PageParamsResolver : HandlerMethodArgumentResolver {

    override fun supportsParameter(methodParameter: MethodParameter): Boolean {
        return methodParameter.parameterType == QueryParams::class.java
    }

    override fun resolveArgument(methodParameter: MethodParameter,
                                 modelAndViewContainer: ModelAndViewContainer?,
                                 nativeWebRequest: NativeWebRequest,
                                 webDataBinderFactory: WebDataBinderFactory?): Any? {


        val page = nativeWebRequest.getParameter("pageNumber")
        val queryParams: QueryParams<Any> = if (page != null && page != "") {// 明确分页查询
            val size = nativeWebRequest.getParameter("pageSize")
            QueryParams(pageNumber = page.toLong(), pageSize = size!!.toInt())
        } else {
            QueryParams()

        }

        val names = nativeWebRequest.parameterNames
        val params = Simple()
        while (names.hasNext()) {
            val name = names.next()
            val value = if(name.endsWith("Array")){
                nativeWebRequest.getParameterValues(name)
            }else{
                nativeWebRequest.getParameter(name)
            }
            params[name] = value as Any
        }
        queryParams.params = params
        return queryParams
    }
}